package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillPre;
import com.topisv.tms.entity.stockchange.StockChangeBill;
import com.topisv.tms.entity.stockchange.StockChangeBillItem;
import com.topisv.tms.repository.EdiGoodsSkuDao;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.repository.stock.preInstorage.InstorageBillPreDao;
import com.topisv.tms.repository.stockChange.StockChangeBillDao;
import com.topisv.tms.repository.stockChange.StockChangeBillItemDao;
import com.topisv.tms.rest.qimen.qmentity.response.stockchange.StockChange;
import com.topisv.tms.rest.qimen.qmentity.response.stockchange.StockChangeItem;
import com.topisv.tms.rest.qimen.qmsend.QmRequestSender;
import com.topisv.tms.rest.qimen.request.RequestMethodType;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.utils.InitProperties;
import com.topisv.tms.utils.rule.TMSTransportRule;

/**
 * 出库单确认接口 create by gaohuan 2015-05-09
 * */
@Component
@Transactional(readOnly =  false)
public class StockChangeService extends QmRequestSender<StockChangeBill>{
	private static final Logger logger = LoggerFactory.getLogger(StockChangeService.class);

	@Autowired
	private EdiGoodsSkuDao ediGoodsSkuDao;
	@Autowired
	private StockChangeBillDao scbDao;
	@Autowired
	private StockChangeBillItemDao scbiDao;
	@Autowired
	private InstorageBillPreDao ibpDao;
	@Autowired
	private EdiOrderDao ediOrderDao;
	
	@Override
	public RequestParams setupParam(RequestParams sendParams) {
		Map<String,String> params = new HashMap<String,String>();
		params.put("method", RequestMethodType.STOCK_CHANGE.getType());
		params.put("format", InitProperties.get("qm.format"));
		params.put("app_key", InitProperties.get("regAppKey"));
		params.put("v", InitProperties.get("qm.v"));
		params.put("sign_method", InitProperties.get("qm.sign_method"));
		params.put("customerId", "");//暂未定
		sendParams.setSecret(InitProperties.get("regAppSecret"));
		sendParams.setParams(params);
		return sendParams;
}

	@Override
	public String execute(StockChangeBill scb,RequestParams sendParams) {
		String sendXml = null;
		if(scb==null){
			logger.info("数据 为空");
			return null;
		}
		List<StockChangeBillItem> scbiList = scbiDao.findByBillCode(scb.getBillCode());
		if(scbiList==null||scbiList.size()==0){
			logger.info("数据 为空");
			return null;
		}
		Map<String,EdiGoodsSku> cacheSku = new HashMap<String,EdiGoodsSku>();
		
		String orderCode = "";
		if("INSTORAGE".equals(scb.getOrderType())) {
			InstorageBillPre ibp = ibpDao.findByBillCode(scb.getOrderCode());
			if(ibp==null){
				return "bill_not_exist";
			}
			orderCode = ibp.getCustomerOrderNo();
		}else {
			EdiOrder ediOrder = ediOrderDao.findByOrdeno(scb.getOrderCode());
			if(ediOrder==null){
				return "bill_not_exist";
			}
			orderCode = ediOrder.getCustomerOrdeno();
		}
		if(StringUtils.isEmpty(orderCode)){
			return "bill_not_exist";
		}
		
		sendParams.getParams().put("customerId", scb.getCustomerCode());
		
		StockChange sc = new StockChange();
		List<StockChangeItem> items = new ArrayList<StockChangeItem>();
		for (StockChangeBillItem scbi : scbiList) {
			StockChangeItem sci = new StockChangeItem();
			EdiGoodsSku ediGoodsSku = getEdiGoodsSku(scb.getCustomerCode(), scbi.getSku(), cacheSku);
			
			sci.setWarehouseCode(scb.getWarehouseCode());
			sci.setRemark(scb.getRemark());
			sci.setQuantity(scbi.getQuantity()+"");
			sci.setProductDate("");
			sci.setProduceCode("");
			sci.setOwnerCode(scb.getCustomerCode());
			sci.setOutBizCode(TMSTransportRule.generateByPreFix("SCOB"));
			//JYCK= 一般交易出库单，HHCK= 换货出库 ，BFCK= 补发出库 PTCK=普通出库单，DBCK=调拨出库 ，QTCK=其他出库， SCRK=生产入库，LYRK=领用入库，CCRK=残次品入库，CGRK=采购入库 ，DBRK= 调拨入库 ，QTRK= 其他入库 ，XTRK= 销退入库 HHRK= 换货入库 CNJG= 仓内加工单 ZTTZ=状态调整单
			String orderType = "";
			if("INSTORAGE".equals(scb.getOrderType())){
				orderType = "CGRK";
			}else {
				orderType = "JYCK";
			}
			sci.setOrderType(orderType);
			sci.setOrderCode(orderCode);
			sci.setItemId(ediGoodsSku.getId()+"");
			sci.setItemCode(ediGoodsSku.getBar());
			sci.setInventoryType(scbi.getInventoryType());
			sci.setExpireDate("");
			sci.setBatchCode("");
			
			items.add(sci);
		}
		sc.setItems(items);
		
		
		StringWriter writer = new StringWriter();
		JAXB.marshal(sc,writer);
		sendXml = writer.toString();
		return sendXml;
	}
	

	public EdiGoodsSku getEdiGoodsSku(String customerCode,String sku,Map<String,EdiGoodsSku> cacheSku){
		EdiGoodsSku ediGoodsSku = null;
		if(cacheSku.get(customerCode+"_"+sku) != null){
			ediGoodsSku = cacheSku.get(customerCode+"_"+sku);
		}else {
			ediGoodsSku = ediGoodsSkuDao.findByCustomerCodeAndSku(customerCode ,sku);
		}
		return ediGoodsSku;
	}
	
}
